<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Api\Controller;

use Common\Controller\AppframeController;

header('Content-Type: text/plain; charset=utf-8');
class LoginController extends AppframeController
{

	/*
    *  用户注册 发送短信
    * */
	function message_new()
	{
		$phone = I("phone");
//		$phone = '18631078756';
		if (!$phone) {
			exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
		}

		//正则验证手机号是否正确
		if (!preg_match("/^1[34578]\d{9}$/", $phone)) {
			exit(json_encode(array('status'=>'10004','data'=>'手机号格式错误')));
		}
		$code = rand(1000, 9999);
		$array['mobile'] = $phone;
		$array['code'] = $code;
		$array['addtime'] = time() + 1800;
		$shortid = M("code")->add($array);

		if ($shortid) {
			$return = $this->app_short_message($phone, $code, $shortid);
			if ($return) {
				exit(json_encode(array('status'=>'200','data'=>'发送成功')));
			} else {
				exit(json_encode(array('status'=>'201','data'=>'发送失败')));
			}
		} else {
			exit(json_encode(array('status'=>'201','data'=>'发送失败')));
		}
	}

	/*
     * 用户注册  短信发送模块
     * */
	function app_short_message($phone, $code, $shortid){
		require_once "./public/duanxin/api_demo/SmsDemo.php";

		ini_set('date.timezone', 'Asia/Shanghai');

		$demo = new \SmsDemo();

		$time = time();

		$response = $demo->sendSms(
			"{$phone}", // 短信接收者
			"SMS_120515164", // 短信模板编号
			Array(  // 短信模板中字段的值
				"code" => "{$code}",
			),
			"{$shortid}"
		);

		$response = (array)$response;

		if ($response['Code'] == "OK") {
			return true;
		} else {
			return false;
		}
	}

	//用户注册
	function zhuce()
	{
		$phone = trim(I("phone"));

		$dat['password'] = trim(I("pass"));

		$code = trim(I("code"));

		if ($code) {
			$codes = M("code")->where("mobile='{$phone}' and code = '{$code}'")->find();
		}
		if (!$codes) {
//			echo "验证码不正确";die;
			exit(json_encode(array('status'=>'10015','data'=>'验证码不正确')));
		} else {
			$dat['last_login_time'] = time();           //最后登录的时间
			$dat['ctime'] = time();                     //创建的时间
			if ($phone) {
				$zhanghao = M("account")->where("phone = {$phone}")->find();
				if ($zhanghao) {
					exit(json_encode(array('status'=>'10005','data'=>'账户已存在')));
				} else {
					$dat['phone'] = $phone;
					$dat['birthday'] = time();
					M("account")->where('phone = {$phone}')->add($dat);
				}
			}

			$zhuce = M("account")->where("phone = '{$phone}'")->find();

			// 获取 Token 开始
			include "./rongyun/master/API/rongcloud.php";
			$appKey = 'kj7swf8okivm2';
			$appSecret = 'TAEhDLABQsMjf';
			$RongCloud = new \RongCloud($appKey,$appSecret);
			$userId = $zhuce['id'];
			$nickname = $phone;
			$head_img =  "123456789";         //随便给的值
			$result = $RongCloud->user()->getToken($userId,$nickname,$head_img);   	// 获取 Token
			$kk = json_decode($result,true);
			$dd['token'] = $kk['token'];
			M("account")->where("phone = $phone")->save($dd);
			// 获取 Token 结束



			if ($zhuce) {
				exit(json_encode(array('status'=>'200','data'=>'注册成功')));
			} else {
				exit(json_encode(array('status'=>'201','data'=>'注册失败')));
			}
		}
	}

	//用户登录  注册用户登录
	function denglu()
	{
		$phone = trim(I("phone"));

		$pass = trim(I("pass"));

		if (!$phone || !$pass) {
			exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
		}
		$zhanghao = M("account")->where("phone = '{$phone}' and password = '{$pass}'")->find();
		 if($zhanghao['is_dongjie']==1){
			 exit(json_encode(array('status'=>'205','data'=>'您的账号正处于冻结状态，请联系客服解冻！')));
		 }

		if (!$zhanghao) {
			exit(json_encode(array('status'=>'10004','data'=>'账号或密码不正确')));
		} else {
			$dat['last_login_time'] = time();
			$dat['last_login_ip'] = get_client_ip();
			M("account")->where("phone = '{$phone}' and password = '{$pass}'")->save($dat);
			$data = M("account")->where("phone = '{$phone}'")->find();



		   //登录  欢迎消息的发送 开始
			include "./rongyun/master/API/rongcloud.php";
			$appKey = 'kj7swf8okivm2';
			$appSecret = 'TAEhDLABQsMjf';
			$RongCloud = new \RongCloud($appKey,$appSecret);
			// 发送单聊消息方法（一个用户向另外一个用户发送消息，单条消息最大 128k。每分钟最多发送 6000 条信息，每次发送用户上限为 1000 人，如：一次发送 1000 人时，示为 1000 条消息。）
			$fromUserId = "1";    //发送人用户 Id
			$toUserId = $zhanghao['id']; //接收用户 Id，可以实现向多人发送消息，每次上限为 1000 人

			$RongCloud->message()->publishPrivate($fromUserId, $toUserId, 'RC:TxtMsg',"{\"content\":\"尊敬的用户您好！欢迎您使用真合拍APP！\",\"extra\":\"\",\"duration\":20}", 'thisisapush', '{\"pushData\":\"\"}', '4', '0', '0', '0', '0');

			if($data){
				exit(json_encode(array('status'=>'200','data'=>$data)));
			}else{
				exit(json_encode(array('status'=>'201','data'=>'登录失败')));
			}
		}
	}

	//第三方用户登录
	function sanfang_denglu(){
		$from = trim(I("from"));
		$uid = trim(I("uid"));    //第三方uid

		if(!$from || !$uid){
			exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
		}

		if($from==1) {
			$dat = M("account")->where("weixin_id = '{$uid}'")->find();
		}elseif($from==2){
			$dat = M("account")->where("qq_id = '{$uid}'")->find();
		}elseif($from==3){
			$dat = M("account")->where("weibo_id = '{$uid}'")->find();
		}


		if ($dat) {

			//登录  欢迎消息的发送 开始
			include "./rongyun/master/API/rongcloud.php";
			$appKey = 'kj7swf8okivm2';
			$appSecret = 'TAEhDLABQsMjf';
			$RongCloud = new \RongCloud($appKey,$appSecret);
			// 发送单聊消息方法（一个用户向另外一个用户发送消息，单条消息最大 128k。每分钟最多发送 6000 条信息，每次发送用户上限为 1000 人，如：一次发送 1000 人时，示为 1000 条消息。）
			$fromUserId = "1";    //发送人用户 Id
			$toUserId = $dat['id']; //接收用户 Id，可以实现向多人发送消息，每次上限为 1000 人

			 $RongCloud->message()->publishPrivate($fromUserId, $toUserId, 'RC:TxtMsg',"{\"content\":\"尊敬的用户您好！欢迎您使用真合拍APP！\",\"extra\":\"\",\"duration\":20}", 'thisisapush', '{\"pushData\":\"\"}', '4', '0', '0', '0', '0');

			exit(json_encode(array('status'=>'200','data'=>$dat)));
		}else{
			exit(json_encode(array('status'=>'201','data'=>'第一次登陆，请验证手机号')));
		}





	}
	//如果第三方是第一次登陆
	function diyici_denglu(){
					$from = trim(I("from"));          //来自 1.微信  2.QQ   3.微博
//                 		$from = '1';
					$phone = trim(I("phone"));        //要验证的手机号
//                 		$phone = '15311428134';
					$code = trim(I("code"));            //验证码
//                 		$code = '1715';
					$uid = trim(I("uid"));                 //第三方id
//					    $uid = 'oMGIk0qfelCVg6cZI4YNOhtBRL4Y';
					if(!$from || !$uid || !$phone || !$code){
						exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
					}

					if ($code) {
						$codes = M("code")->where("mobile='{$phone}' and code = '{$code}'")->find();
					}
					if (!$codes) {
						exit(json_encode(array('status'=>'10015','data'=>'验证码不正确')));
					} else
						if ($from == 1) {
							$dat['last_login_time'] = time();//最后登录的时间
							$dat['last_login_ip'] = get_client_ip();
							$dat['weixin_id'] = $uid;
							$nickname =  trim(I("nickname"));
							$dat['nickname'] = $nickname;
							$dat['sex'] = trim(I("sex"));     //0男   1女  2保密

							$head_img = trim(I("head_img"));   //第三方头像
							$dat['head_img'] = $head_img;
							$dat['ctime'] = time();
							if($phone){
								$data = M("account")->where("phone = '{$phone}'")->find();
							}

							if($data){
								if($data['weixin_id']){
									if($data['weixin_id']==$uid){
										exit(json_encode(array('status'=>'200','data'=>$data)));
									}else{
										exit(json_encode(array('status'=>'10025','data'=>'该手机号已绑定其他微信')));
									}
								}else{
									M("account")->where("id = {$data['id']}")->save($dat);
								}
							}else{

								$dat['phone'] = $phone;
								$dat['birthday'] = time();
								M("account")->add($dat);
							}
						}elseif($from == 2){
							$dat['last_login_time'] = time();//最后登录的时间
							$dat['last_login_ip'] = get_client_ip();
							$dat['qq_id'] = $uid;
							$dat['nickname'] = trim(I("nickname"));
							$dat['sex'] = trim(I("sex"));
							$dat['head_img'] = trim(I("head_img"));
							$dat['ctime'] = time();
							if($phone){
								$data = M("account")->where("phone = '{$phone}'")->find();
							}
							if($data){
								if($data['qq_id']){
									if($data['qq_id']==$uid){
										exit(json_encode(array('status'=>'200','data'=>$data)));
									}else{
										exit(json_encode(array('status'=>'10026','data'=>'该手机号已绑定其他QQ')));
									}
								}else{
									 M("account")->where("id = {$data['id']}")->save($dat);
								}
							}else{
								$dat['phone'] = $phone;
								$dat['birthday'] = time();
								M("account")->add($dat);
							}
						} elseif ($from == 3) {
							$dat['last_login_time'] = time();//最后登录的时间
							$dat['last_login_ip'] = get_client_ip();
							$dat['weibo_id'] = $uid;
							$dat['nickname'] = trim(I("nickname"));
							$dat['sex'] = trim(I("sex"));
							$dat['head_img'] = trim(I("head_img"));
							$dat['ctime'] = time();
							if($phone){
								$data = M("account")->where("phone = '{$phone}'")->find();
							}
							if($data){
								if($data['weibo_id']){
									if($data['weibo_id']==$uid){
										exit(json_encode(array('status'=>'200','data'=>$data)));
									}else{
										exit(json_encode(array('status'=>'10027','data'=>'该手机号已绑定其他微博')));
									}
								}else{
									 M("account")->where("id = {$data['id']}")->save($dat);
								}
							}else{
								$dat['phone'] = $phone;
								$dat['birthday'] = time();
								 M("account")->add($dat);
							}
						}
							  // 获取 Token 开始
							$dataa = M("account")->where("phone = $phone")->find();
							include "./rongyun/master/API/rongcloud.php";
							$appKey = 'kj7swf8okivm2';
							$appSecret = 'TAEhDLABQsMjf';
//							$jsonPath = "jsonsource/";
							$RongCloud = new \RongCloud($appKey,$appSecret);
							$userId = $dataa['id'];
							$nickname =  $dataa['nickname'];
							$head_img =  $dataa['head_img'];

							// 获取 Token 方法
							$result = $RongCloud->user()->getToken($userId,$nickname,$head_img);
							$kk = json_decode($result,true);
							$dd['token'] = $kk['token'];
							M("account")->where("phone = $phone")->save($dd);
							// 获取 Token 结束

		            $zhuce = M("account")->where("phone = $phone")->find();

					if ($zhuce) {
						//登录  欢迎消息的发送 开始
						// 发送单聊消息方法（一个用户向另外一个用户发送消息，单条消息最大 128k。每分钟最多发送 6000 条信息，每次发送用户上限为 1000 人，如：一次发送 1000 人时，示为 1000 条消息。）
						$fromUserId = "1";    //发送人用户 Id
						$toUserId = $zhuce['id']; //接收用户 Id，可以实现向多人发送消息，每次上限为 1000 人
						$RongCloud->message()->publishPrivate($fromUserId, $toUserId, 'RC:TxtMsg',"{\"content\":\"尊敬的用户您好！欢迎您使用真合拍APP！\",\"extra\":\"\",\"duration\":20}", 'thisisapush', '{\"pushData\":\"\"}', '4', '0', '0', '0', '0');

						exit(json_encode(array('status'=>'200','data'=>$zhuce)));
					} else {
						//			echo "登录失败";
						exit(json_encode(array('status'=>'201','data'=>'登录失败')));
					}

				}


   //忘记密码  重设密码  发送短信
	function forget_pass(){
		$phone = I("phone");
//		$phone = '18631078756';
		if(!$phone){
			exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
		}
		//正则验证手机号是否正确
		if(!preg_match("/^1[34578]\d{9}$/", $phone)){
			exit(json_encode(array('status'=>'10004','data'=>'手机号格式错误')));
		}
		$date = M("account")->where("phone = '{$phone}'")->find();
		if(!$date){
			exit(json_encode(array('status'=>'10010','data'=>'手机号未注册')));
		}else{
			$code = rand(1000,9999);
			$array['mobile'] = $phone;
			$array['code'] = $code;
			$array['addtime'] = time()+180;
			$shortid = M("code")->add($array);

			if($shortid){
				$return = $this->app_short_message2($phone,$code,$shortid);
				if($return){
	//				  echo "发送成功";
					exit(json_encode(array('status'=>'200','data'=>'发送成功')));
				}else{
	//				echo "发送失败";
					exit(json_encode(array('status'=>'201','data'=>'发送失败')));
				}
			}else{
	//			echo "发送失败";
				exit(json_encode(array('status'=>'201','data'=>'发送失败')));
			}
		}
	}

   //客户忘记密码 发送短信模板
	function app_short_message2($phone,$code,$shortid){
		require_once "./public/duanxin/api_demo/SmsDemo.php";
		ini_set('date.timezone', 'Asia/Shanghai');
		$demo = new \SmsDemo();
		$time = time();
		$response = $demo->sendSms(
			"{$phone}", // 短信接收者
			"SMS_120515163", // 短信模板编号
			Array(  // 短信模板中字段的值
				"code" => "{$code}",
			),
			"{$shortid}"
		);
		$response = (array)$response;
		if ($response['Code'] == "OK") {
			return true;
		} else {
			return false;
		}
	}

	//忘记密码 保存 确定
	function forget_sav(){
		$phone = trim(I("phone"));
//		$phone = '18631078756';
		$pass =
		$dat['password'] = trim(I("pass"));
//		$dat['password'] = '111111';
		$code = trim(I("code"));

		  if(!$phone  || !$code ){
			  exit(json_encode(array('status'=>'10003','data'=>'缺少参数')));
		  }

		if ($code) {
			$codes = M("code")->where("mobile='{$phone}' and code = '{$code}'")->find();
		}
		if (!$codes) {
			exit(json_encode(array('status'=>'10015','data'=>'验证码不正确')));
		}
		 M("account")->where("phone = '{$phone}'")->save($dat);
		exit(json_encode(array('status'=>'200','data'=>"保存成功")));

	}

}